﻿using CRMBiz;
using CRMWeb.Utilities.Context;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace CRMWeb.Pages.AM.EzidebitService
{
    public partial class GetScheduledPayments : System.Web.UI.Page
    {
        DataSet ds = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                EziDebitService ezidebitservice = new EziDebitService();
                XmlDocument response = ezidebitservice.getScheduledPayments(WebConfigurationManager.AppSettings["EziDebitDigitalKey"], txtDateFrom.Text, txtDateTo.Text, txtEziDebitCustomerID.Text, txtYourSystemReference.Text);
                ds = ConvertXMLtoDataSet(response.InnerXml);
                gvGetScheduledPayments.DataSource = ds.Tables[0];
                gvGetScheduledPayments.DataBind();
                CalculateDishonorFees(ds);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

        public void CalculateDishonorFees(DataSet ds)
        {
            int DishonorFeesCount = 0, TotalDishonor = 0;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                //if (DateTime.Parse(ds.Tables[0].Rows[i]["PaymentDate"].ToString()) < DateTime.Now)
                if (DateTime.Parse(ds.Tables[0].Rows[i]["PaymentDate"].ToString()) < DateTime.Now)
                {
                    DishonorFeesCount = DishonorFeesCount + 1;
                    TotalDishonor = TotalDishonor + 10;
                }
            }
            lblDishonorFees.Text = "Total Numbers of Dishonors are: " + DishonorFeesCount + " Total Amount of Dishonor is: " + TotalDishonor;
        }

        private DataSet ConvertXMLtoDataSet(string response)
        {
            DataSet ds = new DataSet();
            try
            {
                using (StringReader stringReader = new StringReader(response))
                {
                    ds = new DataSet();
                    ds.ReadXml(stringReader);
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return ds;
        }
    }
}